import React, { Component } from 'react'
import PubSub from 'pubsub-js'

export default class List extends Component {

  state = {todos:[
    {id:'001',name:'睡觉',done:true},
    {id:'002',name:'打游戏',done:false},
  ]}

  upChecked = (id)=>{
    return (event)=>{
      const {todos} = this.state
      const newTodos = todos.map((todoObj)=>{
        if(todoObj.id === id) return {...todoObj,done:event.target.checked}
        else return todoObj
      })
      this.setState({todos:newTodos})
    }
  }

  componentDidMount(){
    const {todos} = this.state
    this.token = PubSub.subscribe('Header',(_,todoObj)=>{
      const newTodos = [todoObj,...todos]
      this.setState({todos:newTodos})
    })
    
    this.token2 = PubSub.subscribe('Footer',(_,todoObj)=>{
      const newTodos = [todoObj,...todos]
      this.setState({todos:newTodos})
    })
  }

  componentWillUnmount(){
    PubSub.unsubscribe(this.token,this.token2)
  }

  render() {
    const {todos} = this.state
    return (
      <ul>
        {
          todos.map( todo =>{
            return (
              <li key={todo.id}>
                <label>
                  <input onChange={this.upChecked(todo.id)} checked={todo.done} type="checkbox"/>
                  <span>{todo.name}</span>
                </label>
                <button style={{display:'none'}}>删除</button>
              </li>
            )
          })
        }
      </ul>
    )
  }
}
